package cn.sc.allinpay.allfavour.business.saledetail;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.pai.common.listener.OnPromptListener;
import cn.pai.common.utils.AmtUtils;
import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.base.db.DbDao;
import cn.sc.allinpay.allfavour.business.common.data.CashierData;
import cn.sc.allinpay.allfavour.business.common.data.PosData;
import cn.sc.allinpay.allfavour.business.common.data.SaleCouponData;
import cn.sc.allinpay.allfavour.business.common.data.SaleCouponRecord;
import cn.sc.allinpay.allfavour.module.allin.AllinUtils;
import cn.sc.allinpay.allfavour.module.device.DeviceLogin;
import cn.sc.allinpay.allfavour.module.printer.IPrinter;
import cn.sc.allinpay.allfavour.module.printer.PrintData;
import cn.sc.allinpay.allfavour.module.printer.PrintManager;

/**
 * 售券详情 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class SaleDetailPresenter extends PaiPresenter<SaleDetailContract.View> implements SaleDetailContract.Presenter {

    public static final int REQ_SALE = 0x01;//消费
    public static final int REQ_SCAN = 0x02;//扫码支付
    public static final int REQ_CASH = 0x03;//现金支付

    private SaleDetailModel model = new SaleDetailModel();
    private SaleCouponData saleData;//售券数据
    private BigDecimal paidAmt = BigDecimal.ZERO;//支付金额
    private int saleNum = 0;//售券数量
    private String payType;//支付类型 10:现金  11:银行卡  12:扫码
    private String orderId;//收银宝的订单号
    private SaleCouponRecord record;//售券记录
    private IPrinter printer;


    @Override
    protected Intervenor createIntervenor() {
        return new Intervenor() {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                Bundle bundle = view.getBundle();
                saleData = bundle.getParcelable(Constant.BundleKey.SALECOUPON);
            }

            @Override
            public void onResume() {
                super.onResume();
                DeviceLogin.login(view.getContext());
            }

            @Override
            public void onPause() {
                super.onPause();
                DeviceLogin.logout();
            }

            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (Activity.RESULT_OK == resultCode) {
                    if (data != null) {
                        if (REQ_SALE == requestCode) {//刷卡消费成功
                            view.toast("消费成功");
                        } else if (REQ_SCAN == requestCode) {//扫码支付成功
                            view.toast("扫码支付成功");
                        } else if (REQ_CASH == requestCode) {//现金支付成功
                            view.toast("现金支付成功");
                        }
                        PosData posData = new PosData();
                        posData.setTerminalId(data.getStringExtra("terminalId"));//终端号
                        posData.setMerchantId(data.getStringExtra("merchantId"));//商户id
                        posData.setMerchantName(data.getStringExtra("merchantName"));//商户名称
                        posData.setTransType(data.getStringExtra("transType"));//交易类型
                        posData.setAmount(AmtUtils.changeF2Y(data.getStringExtra("amount")));//金额
                        posData.setTraceNo(data.getStringExtra("traceNo"));//凭证号
                        posData.setBatchNo(data.getStringExtra("batchNo"));//批次号
                        posData.setReferenceNo(data.getStringExtra("referenceNo"));//参考号
                        posData.setDateTime(data.getStringExtra("dateTime"));//交易时间 格式yyyyMMddHHmmss
                        posData.setCardNo(data.getStringExtra("cardNo"));//卡号
                        posData.setIssue(data.getStringExtra("issue"));//发卡行
                        posData.setTransactionNumber(data.getStringExtra("transactionNumber"));//交易单号
//                        posData.setOrderpayway(data.getStringExtra("orderpayway"));//订单支付方式    银行卡-01|微信-02|支付宝-03
                        //保存交易数据
                        saveRecord(posData);
                        reqSaleCoupon();
                    } else {
                        view.toast("交易参数返回为空");
                    }

                } else {
                    if (data != null) {
                        String reson = data.getStringExtra("reason");
                        if (!TextUtils.isEmpty(reson)) {
                            view.toast(reson);
                        } else {
                            view.toast("交易失败");
                        }
                    } else {
                        view.toast("交易失败");
                    }
                }
            }
        };
    }

    @Override
    public void start() {
        view.showName(saleData.getName());
        //0金额 1抵扣 2计次
        if (0 == saleData.getAmtType()) {
            view.showType("类型：金额券");
            view.showInventory("库存：" + saleData.getTotCoup());
            view.showPriceAmt("面额：" + AmtUtils.changeF2Y(saleData.getAmt()));
            view.showNumTitle("发券数量：");
        } else {
            if (1 == saleData.getAmtType()) {
                view.showType("类型：抵扣券");
                view.showNumTitle("发券数量：");
            } else {
                view.showType("类型：计次券");
                view.showNumTitle("发券次数：");
            }
            view.showInventory("库存：" + saleData.getTotCoup() + saleData.getUnit());
            view.showPriceAmt(null);
        }
        view.showSalePrice("售价：" + AmtUtils.changeF2Y(saleData.getPrice()));
        view.showExplain(saleData.getDesc());
        view.showNumber(String.valueOf(saleNum));
        view.showPaidAmt(AmtUtils.formatY(paidAmt));
        additNumber();
    }

    @Override
    public void reduceNumber() {
        if (saleNum > 0) {
            saleNum -= 1;
            saleData.setUseNum(saleNum);
            view.showNumber(String.valueOf(saleNum));
            paidAmt = new BigDecimal(saleData.getPrice()).multiply(new BigDecimal(saleNum)).divide(new BigDecimal(100));
            view.showPaidAmt(AmtUtils.formatY(paidAmt));
        }
    }

    @Override
    public void additNumber() {
        if (saleNum < Integer.valueOf(saleData.getTotCoup())) {
            saleNum += 1;
            saleData.setUseNum(saleNum);
            view.showNumber(String.valueOf(saleNum));
            paidAmt = new BigDecimal(saleData.getPrice()).multiply(new BigDecimal(saleNum)).divide(new BigDecimal(100));
            view.showPaidAmt(AmtUtils.formatY(paidAmt));
        }
    }

    @Override
    public void callSale() {
        if (saleNum == 0) {
            view.prompt("售券数量不能为空");
            return;
        }
        payType = "11";//支付方式
        reqCreateOrder();
    }

    @Override
    public void callScan() {
        if (saleNum == 0) {
            view.prompt("售券数量不能为空");
            return;
        }
        payType = "12";//支付方式
        reqCreateOrder();
    }

    /**
     * 创建订单接口
     */
    private void reqCreateOrder() {
        view.loading("订单创建中...");
        model.reqMarketCreateOrder(paidAmt.toString(), new MpCallBack<String, String>() {
            @Override
            public void onSuccess(String resp) {
                orderId = resp;
                view.loaded();
                //10:现金  11:银行卡  12:扫码
                if ("11".equals(payType)) {
                    AllinUtils.callSale(view.getActivity(), resp, paidAmt.toString(), REQ_SALE);
                } else if ("12".equals(payType)) {
                    AllinUtils.callScan(view.getActivity(), resp, paidAmt.toString(), REQ_SCAN);
                }
            }

            @Override
            public void onFailure(String response, String message) {
                view.loaded();
                view.prompt(message);
            }
        });
    }

    /**
     * 保存售券流水
     */
    private void saveRecord(PosData posData) {
        DbDao<SaleCouponRecord> dbDao = model.getDao(SaleCouponRecord.class);
        CashierData cashierData = model.getGlobal().getCashierData();
        record = new SaleCouponRecord();
        record.setTransNo(orderId + saleData.getId());//流水号
        record.setOrderId(orderId);//订单号,营销前置订单号
        record.setTransAmt(posData.getAmount());//交易金额
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        record.setTransDate(time.substring(0, 8));
        record.setTransTime(time.substring(8));
        record.setTransType(posData.getTransType());
        record.setState(1);//支付状态  0：支付中 1:支付成功
        record.setSellState(0);//销账状态  0:销账中 1:销账成功
        record.setOperator(cashierData.getCashierNo());//操作员号码
        record.setOperatorName(cashierData.getCashierName());//操作员名称
        record.setCouponName(saleData.getName());//售券名称
        record.setCouponNum(saleNum);//售券数量
        record.setCouponType(saleData.getAmtType());//售券类型
        record.setCouponPrice(AmtUtils.changeF2Y(saleData.getPrice()));//售价
        record.setCouponUnit(saleData.getUnit());//单位
        record.setSaleCouponData(JSON.toJSONString(saleData));//就是SaleCouponData对象的json
        record.setPosData(JSON.toJSONString(posData));//就是PosData对象的json
        dbDao.add(record);
    }

    /**
     * 售券订单接口
     */
    private void reqSaleCoupon() {
        view.loading("售券中...");
        List<SaleCouponData> saleList = new ArrayList<>();
        saleList.add(saleData);
        model.reqSaleCoupon(orderId, AmtUtils.changeY2F(paidAmt.toString()), payType, saleList, new MpCallBack<JSONObject, String>() {
            @Override
            public void onSuccess(JSONObject resp) {
                view.loaded();
                JSONObject data = resp.getJSONObject("data");
                String seqNum = data.getString("seqNum");
                String trsTime = data.getString("retTime");
                String url = data.getString("url");
                DbDao<SaleCouponRecord> dbDao = model.getDao(SaleCouponRecord.class);
                record.setTransDate(trsTime.substring(0, 8));
                record.setTransTime(trsTime.substring(8));
                record.setSeqNum(seqNum);
                record.setSellState(1);
                record.setDesc(url);
                dbDao.update(record);
                print();
            }

            @Override
            public void onFailure(String response, String message) {
                view.loaded();
                view.prompt(false, message + ",是否继续售券？", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        reqSaleCoupon();
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.finish();
                    }
                });
            }
        });
    }


    public void print() {
        //因为onActivityResult回来没有立即执行onResume方法
        DeviceLogin.login(view.getContext());
        view.loading("售券成功，正在打印...");
        PrintData data = new PrintData();
        data.setMerchantName(model.getGlobal().getConfigData().getMerName());
        data.setTerminalId(model.getGlobal().getConfigData().getTerId());
        data.setOperNo(record.getOperator());
        data.setOperName(record.getOperatorName());
        data.setTime(record.getTransDate()+record.getTransTime());
        data.setTransName("售券");
        data.setCouponSeqNum(record.getSeqNum());
        data.setCouponName(record.getCouponName());
        data.setCouponType(record.getCouponType());
        data.setCouponUseNum(record.getCouponNum());
        data.setCouponPrice(record.getCouponPrice());
        data.setCouponUrl(record.getDesc());
        printer = PrintManager.createPrinter(PrintManager.PRINT_SALE, data);
        printer.print(new IPrinter.OnPrintListener() {
            @Override
            public void onStart(int step) {

            }

            @Override
            public void onSuccess(int step) {
                view.loaded();
                view.prompt(false, "打印成功", new OnPromptListener("确定") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.setResult(Activity.RESULT_OK, null);
                        view.finish();
                    }
                });
            }

            @Override
            public void onFail(int code, String msg) {
                view.loaded();
                view.prompt(false, msg + ",是否继续打印", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        print();
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.setResult(Activity.RESULT_OK, null);
                        view.finish();
                    }
                });
            }
        });
    }
}
